package com.ruoyi.form.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.form.base.StringUtils;
import com.ruoyi.form.domain.AxModelField;
import com.ruoyi.form.domain.AxField;
import com.ruoyi.form.mapper.AxModelFieldMapper;
import com.ruoyi.form.service.IAxModelFieldService;
import com.ruoyi.form.service.IAxFieldService;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author LZF
 * @date 2025-07-18
 */
@Service
public class AxModelFieldServiceImpl extends ServiceImpl<AxModelFieldMapper, AxModelField> implements IAxModelFieldService {

    @Autowired
    private AxModelFieldMapper axModelFieldMapper;
    @Autowired
    private IAxFieldService axFieldService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public AxModelField selectAxModelFieldById(String id) {
        return axModelFieldMapper.selectAxModelFieldById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param axModelField 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<AxModelField> selectAxModelFieldList(AxModelField axModelField) {
        return axModelFieldMapper.selectAxModelFieldList(axModelField);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param axModelField 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertAxModelField(AxModelField axModelField) {
                axModelField.setCreateTime(DateUtils.getNowDate());
            axModelField.setCreateTime(DateUtils.getNowDate());
            return axModelFieldMapper.insert(axModelField);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param axModelField 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAxModelField(AxModelField axModelField) {
                axModelField.setUpdateTime(DateUtils.getNowDate());
        return axModelFieldMapper.updateAxModelField(axModelField);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAxModelFieldByIds(String[] ids) {
        return axModelFieldMapper.deleteAxModelFieldByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAxModelFieldById(String id) {
        return axModelFieldMapper.deleteAxModelFieldById(id);
    }

    /*****************************************************************************************************************/
    /**
     * 页面配置： 生成筛选项表单
     * @return
     */
    @Override
    public List<JSONObject> createFilterForm(String modelId) {
        QueryWrapper<AxModelField> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model_id", modelId);
        queryWrapper.isNotNull("filter_position");
        queryWrapper.ne("filter_position","");
        queryWrapper.orderByAsc("filter_sort_num");
        List<AxModelField> list = axModelFieldMapper.selectList(queryWrapper);
        List<JSONObject> reList = new ArrayList<>();
        for (AxModelField axModelField : list){
            JSONObject jsonObject;
            if("checkbox".equals(axModelField.getFilterType()) || "select".equals(axModelField.getFilterType())|| "radio".equals(axModelField.getFilterType())){
                // 查询字典
                if (StringUtils.isEmpty(axModelField.getFieldId())){
                    continue;
                }
                AxField field = axFieldService.selectAxFieldById(axModelField.getFieldId());
                SysDictData queryDictData = new SysDictData();
                queryDictData.setDictType(field.getFormDictType());
                List<SysDictData> datas = sysDictDataService.selectDictDataList(queryDictData);
                JSONArray jsonArray = new JSONArray();
                for (SysDictData dictData:datas){
                    JSONObject dict = JSONObject.parseObject("{'label':'"+dictData.getDictLabel()+"','value':'"+dictData.getDictValue()+"'}");
                    jsonArray.add(dict);
                }
                jsonObject = JSONObject.parseObject("{'label':'"+ axModelField.getName()+"'," +
                        "'type':'"+ axModelField.getFilterType()+"','key':'"+ axModelField.getId()+"','formItemWidth':"+ axModelField.getFormItemWidth()+",'fieldId':'"+ axModelField.getFieldId()+"'," +
                        "'select':"+jsonArray.toJSONString()+",'filterSortNum':"+ axModelField.getFilterSortNum()+",'labelWidth':"+ axModelField.getLabelWidth()+"}");
            } else{

                jsonObject = JSONObject.parseObject("{'label':'"+ axModelField.getName()+"'," +"'formItemWidth':"+ axModelField.getFormItemWidth()+",'fieldId':'"+ axModelField.getFieldId()+"'," +
                        "'type':'"+ axModelField.getFilterType()+"','key':'"+ axModelField.getId()+"','filterSortNum':"+ axModelField.getFilterSortNum()+",'labelWidth':"+ axModelField.getLabelWidth()+"}");

            }
            reList.add(jsonObject);
        }
        return reList;
    }

    /**
     * 查询属性关联模型
     * @param fieldIds
     * @return
     */
    @Override
    public List<Map<String, Object>> selectFieldAccTemp(List<String> fieldIds) {
        return axModelFieldMapper.selectFieldAccTemp(fieldIds);
    }

    /**
     * 查询表格显示列表 包含propertyName
     * @param bo 筛选条件
     * @return JSONObject json对象
     */
    @Override
    public List<JSONObject> queryListAndPropertyName(AxModelField bo) {
        LambdaQueryWrapper<AxModelField> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(true, AxModelField::getSortNum);
        List<AxModelField> list = axModelFieldMapper.selectList(lqw);
        List<JSONObject> result = new ArrayList<>();
        for (AxModelField b:list){
            if (!StringUtils.isEmpty(b.getFieldId())){
                // 获取格式化后的属性code
                AxField field = axFieldService.selectAxFieldById(b.getFieldId());
                // 获取字典数据
                JSONObject jsonObject;
                if (!StringUtils.isEmpty(field.getFormDictType())){
                    SysDictData dictData = new SysDictData();
                    dictData.setDictType( field.getFormDictType());
                    List<SysDictData> dicts = sysDictDataService.selectDictDataList(dictData);
                    jsonObject = JSONObject.parseObject("{'basicCode':'" + axFieldService.getPropertyName(field)+
                            "','isReadOnly':'" + field.getIsReadOnly() + "','jsRequired':'" + field.getJsRequired()
                            + "','label':'" + b.getName() + "','dictList':" + JSONArray.copyOf(dicts) + ",'formTypeName':'" + field.getFormTypeName()+"'}");
                } else{
                    jsonObject = JSONObject.parseObject("{'basicCode':'" + axFieldService.getPropertyName(field)+
                            "','isReadOnly':'" + field.getIsReadOnly() + "','jsRequired':'" + field.getJsRequired() + "','label':'" + b.getName()
                            + "','formTypeName':'" + field.getFormTypeName()+"'}");
                }
                jsonObject.put("formwidth", field.getFormWidth());
                // 获取上传信息
                if ("upload".equals(field.getFormTypeName())){
                    jsonObject.put("uploadTypeId",field.getUploadTypeId());
                    jsonObject.put("fieldId",field.getId());
                }
                result.add(jsonObject);
            }
        }
        return result;
    }
    @Override
    public List<AxModelField> queryRefList(AxModelField bo) {
        QueryWrapper<AxModelField> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("show_flag", "1");
        queryWrapper.isNull("filter_position");
        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(bo.getModelId())) {
            queryWrapper.eq("model_id", bo.getModelId());
        }
        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(bo.getParentId())) {
            queryWrapper.eq("parent_id", bo.getParentId());
        }
        queryWrapper.and(wrapper -> wrapper.isNull("attach_flag").or().eq("attach_flag", "0"));
        List<AxModelField> bussModelFields = axModelFieldMapper.selectList(queryWrapper);
        return bussModelFields;
    }
    private LambdaQueryWrapper<AxModelField> buildQueryWrapper(AxModelField bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AxModelField> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSortNum() != null, AxModelField::getSortNum, bo.getSortNum());
        lqw.like(StringUtils.isNotBlank(bo.getName()), AxModelField::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getShowFlag()), AxModelField::getShowFlag, bo.getShowFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getFieldId()), AxModelField::getFieldId, bo.getFieldId());
        lqw.eq(StringUtils.isNotBlank(bo.getModelId()), AxModelField::getModelId, bo.getModelId());
        lqw.eq(StringUtils.isNotBlank(bo.getFilterPosition()), AxModelField::getFilterPosition, bo.getFilterPosition());
        lqw.eq(bo.getFilterSortNum() != null, AxModelField::getFilterSortNum, bo.getFilterSortNum());
        lqw.eq(StringUtils.isNotBlank(bo.getFilterType()), AxModelField::getFilterType, bo.getFilterType());
        lqw.eq(bo.getShowNum() != null, AxModelField::getShowNum, bo.getShowNum());
        lqw.eq(StringUtils.isNotBlank(bo.getFieldCode()), AxModelField::getFieldCode, bo.getFieldCode());
        lqw.eq(bo.getFormSortnum() != null, AxModelField::getFormSortnum, bo.getFormSortnum());
        lqw.eq(bo.getColWidth() != null, AxModelField::getColWidth, bo.getColWidth());
        lqw.eq(StringUtils.isNotBlank(bo.getParentId()), AxModelField::getParentId, bo.getParentId());
        return lqw;
    }
}
